package com.fcat.common.user.util;

import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.FileInputStream;
import java.util.*;

/**
 * @BelongsProject: fcat-project
 * @BelongsPackage: com.fcat.project.main.util
 * @Author: 
 * @CreateTime: 2020-06-06 16:12
 * @Description:
 */
@Slf4j
public class SftpUtil {
    //@Value("${host.ip}")
    private static String ip = "120.25.233.241";
    //@Value("${host.port}")
    private static String port = "22";
    //@Value("${host.username}")
    private static String username = "root";
    //@Value("${host.password}")
    private static String password = "Mictest200527";
    private static String projectPath = "/root";
    private static Session session = null;
    private static Channel channel = null;


    public class SFTPConstants {
        public static final String SFTP_REQ_HOST = "host";
        public static final String SFTP_REQ_PORT = "port";
        public static final String SFTP_REQ_USERNAME = "username";
        public static final String SFTP_REQ_PASSWORD = "password";
        public static final int SFTP_DEFAULT_PORT = 22;
    }

    /**
     * 遍历项目所有模块jar包的绝对路径
     *
     * @return
     */
    static List<String> getProjectModuleJarPaths() {
        List<String> jarPathList = new ArrayList<>();
        //遍历项目的模块
        String localProjectPath = System.getProperty("user.dir");
        File projectFile = new File(localProjectPath);
        File[] files = projectFile.listFiles();
        for (File file : files) {
            if (!file.getName().contains(".") && file.isDirectory()) {
                String str = localProjectPath + "/" + file.getName() + "/target/" + file.getName() + ".jar";
                File jarFile = new File(str);
                if (jarFile.exists()) {
                    log.info("存在 " + jarFile.getAbsolutePath());
                    jarPathList.add(jarFile.getAbsolutePath());
                } else {
                    log.error("不存在 " + jarFile.getAbsolutePath());
                }
            }
        }
        return jarPathList;
    }

    public ChannelSftp getChannel(Map<String, String> sftpDetails, int timeout) throws JSchException {
        String ftpHost = sftpDetails.get(SFTPConstants.SFTP_REQ_HOST);
        String port = sftpDetails.get(SFTPConstants.SFTP_REQ_PORT);
        String ftpUserName = sftpDetails.get(SFTPConstants.SFTP_REQ_USERNAME);
        String ftpPassword = sftpDetails.get(SFTPConstants.SFTP_REQ_PASSWORD);

        int ftpPort = SFTPConstants.SFTP_DEFAULT_PORT;
        if (port != null && !port.equals("")) {
            ftpPort = Integer.valueOf(port);
        }

        JSch jsch = new JSch(); // 创建JSch对象
        session = jsch.getSession(ftpUserName, ftpHost, ftpPort); // 根据用户名，主机ip，端口获取一个Session对象
        log.debug("Session created.");
        if (ftpPassword != null) {
            session.setPassword(ftpPassword); // 设置密码
        }
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config); // 为Session对象设置properties
        session.setTimeout(timeout); // 设置timeout时间
        session.connect(); // 通过Session建立链接
        log.debug("Session connected.");

        log.debug("Opening Channel.");
        channel = session.openChannel("sftp"); // 打开SFTP通道
        channel.connect(); // 建立SFTP通道的连接
        log.debug("Connected successfully to ftpHost = " + ftpHost + ",as ftpUserName = " + ftpUserName
                + ", returning: " + channel);
        return (ChannelSftp) channel;
    }

    public void closeChannel() throws Exception {
        if (channel != null) {
            channel.disconnect();
        }
        if (session != null) {
            session.disconnect();
        }
    }

    //120.25.233.241",22,"root","Mictest200527");

    /**
     *
     */
    public static void uploadJarFile(List<String> moduleNameList) {
        Boolean bFilter = false;
        if (!CollectionUtils.isEmpty(moduleNameList)) {
            bFilter = true;
        }
        try {
            String localProjectPath = System.getProperty("user.dir");

            Map<String, String> sftpDetails = new HashMap<String, String>();
            // 设置主机ip，端口，用户名，密码
            sftpDetails.put(SFTPConstants.SFTP_REQ_HOST, ip);
            sftpDetails.put(SFTPConstants.SFTP_REQ_PORT, port);
            sftpDetails.put(SFTPConstants.SFTP_REQ_USERNAME, username);
            sftpDetails.put(SFTPConstants.SFTP_REQ_PASSWORD, password);

            List<String> jarFileList = getProjectModuleJarPaths();
            if (!CollectionUtils.isEmpty(jarFileList)) {
                SftpUtil sftpUtil = new SftpUtil();
                ChannelSftp chSftp = sftpUtil.getChannel(sftpDetails, 60000);
                //s:::::E:\svn-53\project\trunk\fcat-project\project-netty\target\project-netty.jar
                //dst:::/root/project-netty.jar
                for (String s : jarFileList) {
                    int index = s.lastIndexOf('\\');
                    if (bFilter) {
                        if (!moduleNameList.contains(s.substring(index + 1).replaceAll(".jar", ""))) {
                            continue;
                        }
                    }
                    FileInputStream inputStream = new FileInputStream(s);
                    String dst = projectPath + "/" + s.substring(index + 1); // 目标文件名
                    if (inputStream != null) {
                        log.info("sftp 正在传输文件......:" + s);
                        chSftp.put(inputStream, dst);
                        log.info("sftp 传输文件完成:" + s + " 到centos: " + dst);
                    }
                }
                chSftp.quit();
                sftpUtil.closeChannel();
                log.info("sftp 传输所有文件完成:");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        List<String> moduleNameList = new ArrayList<>();
        moduleNameList.add("common-user");
        //1)只上传project-main模块jar
        uploadJarFile(moduleNameList);
        //2)上传全部模块jar
        //uploadJarFile(null);
    }

}